package com.ruoyi.web.controller.rest.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.WebUser;
import com.ruoyi.system.domain.WebUserAccount;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 微信公众号菜单 信息操作处理
 *
 * @author liupan
 * @date 2019-03-25
 */
@Api(tags = "用户中心")
@RestController
@RequestMapping("/rest/user/center")
public class _UserCenterController extends BaseController {
    @Autowired
    private IWebUserService iWebUserService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IWebUserAccountService iWebUserAccountService;
    @Autowired
    private IWebUserScoreAwardService iWebUserScoreAwardService;
    @Autowired
    private IWebUserRecommendAwardService iWebUserRecommendAwardService;
    @Autowired
    private ISysDeptService deptService;


    @ApiOperation(value = "保存用户基本信息" , notes = "nickename:昵称，realname：真实姓名，headPic：头像地址,mobile:手机号")
    @PostMapping()
    public AjaxResult update(Integer userId, WebUser user) {
        if (userId == null) {
            return error("userId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        if (StringUtils.isNotEmpty(user.getNickname()))
            userData.setNickname(user.getNickname());
        if (StringUtils.isNotEmpty(user.getHeadPic()))
            userData.setHeadPic(user.getHeadPic());
        if (StringUtils.isNotEmpty(user.getRealname()))
            userData.setRealname(user.getRealname());
        if (StringUtils.isNotEmpty(user.getMobile()))
            userData.setMobile(user.getMobile());
        if (StringUtils.isNotEmpty(user.getSex()))
            userData.setSex(user.getSex());

        iWebUserService.saveOrUpdate(userData);
        return AjaxResult.success();
    }

//    @ApiOperation(value = "保存用户身份及银行卡信息" , notes = "idcard:身份证号,idCardA:身份证正面,idCardA:身份证反面,bindType:1银行卡 2支付宝 ,bankType:开户行,bankNo:银行卡号,alipayNo:支付宝号")
//    @PutMapping()
    public AjaxResult update2(@RequestBody WebUserAccount account) {
        Long userId = account.getUserId();
        if (userId == null) {
            return error("userId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        WebUserAccount accountData = iWebUserAccountService.getOne(new QueryWrapper<WebUserAccount>().eq("user_id",userId));
        if(accountData != null){
            if (StringUtils.isNotEmpty(account.getIdcard()))
                accountData.setIdcard(account.getIdcard());
            if (StringUtils.isNotEmpty(account.getIdCardA()))
                accountData.setIdCardA(account.getIdCardA());
            if (StringUtils.isNotEmpty(account.getIdCardB()))
                accountData.setIdCardB(account.getIdCardB());
            if (account.getBindType() != null)
                accountData.setBindType(account.getBindType());
            if (StringUtils.isNotEmpty(account.getBankType()))
                accountData.setBankType(account.getBankType());
            if (StringUtils.isNotEmpty(account.getBankNo()))
                accountData.setBankNo(account.getBankNo());
            if (StringUtils.isNotEmpty(account.getAlipayNo()))
                accountData.setAlipayNo(account.getAlipayNo());
            iWebUserAccountService.saveOrUpdate(accountData);

            if(StringUtils.isNotEmpty(account.getRealname())){
                if(StringUtils.isNotEmpty(userData.getRealname())){
                    userData.setRealname(account.getRealname());
                }
            }
            if(StringUtils.isNotEmpty(account.getMobile())){
                if(StringUtils.isNotEmpty(userData.getMobile())){
                    userData.setMobile(account.getMobile());
                }
            }
            this.iWebUserService.saveOrUpdate(userData);
        }
        return AjaxResult.success();
    }

    /**
     * 会员信息
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "获取用户基本信息" , notes = "nickename:昵称，realname：真实姓名，headPic：头像地址,mobile:手机号" +
            ",普通用户没有审核状态，回收员等身份有审核状态信息")
    @GetMapping("{userId}")
    public AjaxResult userBaseInfo(@PathVariable("userId") Integer userId) {
        if (userId == null) {
            return error("userId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        Map<String, Object> userMap = iWebUserService.getMap(new QueryWrapper<WebUser>()
                .select("id" , "username" ,"user_type" , "head_pic" , "nickname" , "realname" , "mobile",
                        "real_auth","score","earnings","status","sex")
        .eq("id",userId));
        if("1".equals(userMap.get("user_type"))){
            userMap.put("userTypeName","会员用户");
        } else if("2".equals(userMap.get("user_type"))){
            userMap.put("userTypeName","回收员");
        }else if("3".equals(userMap.get("user_type"))){
            userMap.put("userTypeName","管理员");
        }else if("4".equals(userMap.get("user_type"))){
            userMap.put("userTypeName","快递员");
        }else if("5".equals(userMap.get("user_type"))){
            userMap.put("userTypeName","商家");
        }
        if("0".equals(userMap.get("real_auth").toString()) && !"1".equals(userMap.get("user_type"))){
            userMap.put("realAuthName","未实名");
        } else if("1".equals(userMap.get("real_auth").toString())){
            userMap.put("realAuthName","审核中");
        }else if("2".equals(userMap.get("real_auth").toString())){
            userMap.put("realAuthName","完成审核");
        }else if("3".equals(userMap.get("real_auth").toString())){
            userMap.put("realAuthName","审核未通过");
        }

        int orderCount= 0;
        userMap.put("orderCount",orderCount);
        Integer earnings = (Integer)userMap.get("earnings");
        if(earnings != null){
            userMap.put("earnings",earnings / 100);
        }

        if(userData.getDeptId() != null){
            SysDept dept = deptService.selectDeptById(userData.getDeptId());
            userMap.put("shopName",dept.getDeptName());
        }else{
            userMap.put("shopName","");
        }


        return AjaxResult.success(userMap);
    }

    @ApiOperation(value = "获取用户身份信息" , notes = "idcard:身份证号,idCardA:身份证正面,idCardA:身份证反面")
    @GetMapping("identity/{userId}")
    public AjaxResult userIdentity(@PathVariable("userId") Integer userId) {
        if (userId == null) {
            return error("userId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        Map<String, Object> userMap = iWebUserAccountService.getMap(new QueryWrapper<WebUserAccount>()
                .select("idcard" ,"id_card_a" , "id_card_b")
                .eq("user_id",userId));
        return AjaxResult.success(userMap);
    }

//    @ApiOperation(value = "获取用户银行卡信息" , notes = "bindType:1银行卡 2支付宝 ,bankType:开户行,bankNo:银行卡号,alipayNo:支付宝号")
//    @GetMapping("bank/{userId}")
    public AjaxResult userBankInfo(@PathVariable("userId") Integer userId) {
        if (userId == null) {
            return error("userId不能为null");
        }
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        Map<String, Object> userMap = iWebUserAccountService.getMap(new QueryWrapper<WebUserAccount>()
                .select("idcard" ,"bank_type" , "bank_no", "alipay_no")
                .eq("user_id",userId));
        userMap.put("realname",userData.getRealname());
        userMap.put("mobile",userData.getMobile());
        return AjaxResult.success(userMap);
    }


    @ApiOperation(value = "通用上传请求" , notes = "返回图片地址")
    @PostMapping("upload")
    @ApiImplicitParam(name = "userId" , value = "用户ID" , required = true)
    public AjaxResult uploadFile(Integer userId, MultipartFile file) throws Exception {
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName" , fileName);
            ajax.put("url" , url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    @ApiOperation(value = "用户的佣金记录",notes = "order_no:订单编号,create_time:获得时间,amount:金额,nickname:用户昵称")
    @GetMapping("recommend/list/{userId}")
    @ApiImplicitParam(name = "userId" , value = "用户ID" , required = true)
    public AjaxResult recommendList(@PathVariable Integer userId) throws Exception {
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        List<Map<String,Object>> data = iWebUserRecommendAwardService.selectRecommendList(userId);
        return AjaxResult.success(data);
    }

    @ApiOperation(value = "用户的积分记录",notes = "order_no:订单编号,create_time:获得时间,amount:积分,nickname:用户昵称")
    @GetMapping("score/list/{userId}")
    @ApiImplicitParam(name = "userId" , value = "用户ID" , required = true)
    public AjaxResult scoreList(@PathVariable Integer userId) throws Exception {
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        List<Map<String,Object>> data = iWebUserScoreAwardService.selectScoreList(userId);
        return AjaxResult.success(data);
    }

    @ApiOperation(value = "用户的推广记录",notes = "parent_time:推荐 ,nickname:用户昵称")
    @GetMapping("tuiguang/list/{userId}")
    @ApiImplicitParam(name = "userId" , value = "用户ID" , required = true)
    public AjaxResult tuiguanglist(@PathVariable Integer userId) throws Exception {
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        List<Map<String,Object>> data = iWebUserService.listMaps(new QueryWrapper<WebUser>()
                .eq("parent_id",userId)
                .select("nickname,parent_time,head_pic"));
        return AjaxResult.success(data);
    }
}
